package utils;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class PdfUtils {
    
    public static void addPageNum(String templatePath, String fileName) {
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;
        try {
            // 读取PDF模板表单
            reader = new PdfReader(templatePath);
            // 字节数组流，用来缓存文件流
            bos = new ByteArrayOutputStream();
            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            // 获取新生成的PDF表单
            AcroFields form = stamper.getAcroFields();
            // 给表单生成中文字体，这里采用系统字体，不设置的话，中文显示会有问题
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);
            // 表明该PDF不可修改
            stamper.setFormFlattening(true);
            // 关闭资源
            stamper.close();
            // 将ByteArray字节数组中的流输出到out中（即输出到浏览器）
            Document doc = new Document();
            // 保存到本地
            out = new FileOutputStream(fileName);
           // PdfWriter writer = PdfWriter.getInstance(doc, out);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            int num = reader.getNumberOfPages();
            System.out.println("总页数：" + num);
            // 页面数是从1开始的
            BaseFont base =font;
            for (int i = 0; i < num;) {
                int ii=++i;
                PdfImportedPage page = copy.getImportedPage(reader, ii);
                PdfCopy.PageStamp stamp = copy.createPageStamp(page);
                Font f = new Font(base);
                f.setSize(9);
                // 添加页眉 (文字页眉，居中) 偶数
                if(ii%2==0){
                    ColumnText.showTextAligned(stamp.getOverContent(),  Element.ALIGN_TOP, new Phrase(ii+"", f), 72f, 807, 0);
                }else{
                    ColumnText.showTextAligned(stamp.getOverContent(),  Element.ALIGN_TOP, new Phrase(ii+"", f), 514f, 807, 0);
                }
                stamp.alterContents();
                copy.addPage(page);

            }
            doc.close();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void addFirstPage(String templatePath, String fileName) {
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;
        try {
            // 读取PDF模板表单
            reader = new PdfReader(templatePath);
            // 字节数组流，用来缓存文件流
            bos = new ByteArrayOutputStream();
            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            // 获取新生成的PDF表单
            AcroFields form = stamper.getAcroFields();
            // 给表单生成中文字体，这里采用系统字体，不设置的话，中文显示会有问题
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);
            // 表明该PDF不可修改
            stamper.setFormFlattening(true);
            // 关闭资源
            stamper.close();
            // 将ByteArray字节数组中的流输出到out中（即输出到浏览器）
            Document doc = new Document();
            // 保存到本地
            out = new FileOutputStream(fileName);
            // PdfWriter writer = PdfWriter.getInstance(doc, out);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            int num = reader.getNumberOfPages();
            PdfImportedPage page = copy.getImportedPage(reader, 1);
            copy.addPage(page);
            doc.close();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    public static void createPDF(File file, int lavel,String directory) {
        File file1 = new File(file.getPath() + "\\"+directory);
        System.out.println(file1.getPath() );
        if (file1.exists() && file1.isDirectory()) {

            FileUtils.delFolder(file1.getPath());
            System.out.println("已删除new文件夹" + file.getPath() + "\\"+directory);
        }
        File[] files = file.listFiles();
        for (File f : files) {
            String s = "";
            for (int i = 0; i <= lavel; i++) {
                s += "-";
            }
            if (f.isFile()) {

                if (!FileUtil.exist(f.getParent() + "\\"+directory+"\\")) {
                    FileUtil.mkdir(f.getParent() + "\\"+directory+"\\");
                }
                if (f.getName().contains(".pdf")) {
                    System.out.println(f.getParent() + "\\" + f.getName() + "================开始");
                    if(directory.equals("new")){
                        PdfUtils.addPageNum(f.getPath(), f.getParent() + "\\"+directory+"\\" + f.getName());
                    }else{
                        PdfUtils.addFirstPage(f.getPath(), f.getParent() + "\\"+directory+"\\" + f.getName());
                    }

                    System.out.println(f.getParent() + "\\" + f.getName() + "================成功");
                }

            } else {
                System.out.println(s + f.getName());
                createPDF(f, lavel + 2,directory);
            }
        }
    }



    public static void main(String[] args) {
        String orgPdfPath = "C:\\Users\\jxq\\Desktop\\1.pdf" ;
        String outputPdfPath = "C:\\Users\\jxq\\Desktop\\2.pdf" ;
        PdfUtils.addPageNum(orgPdfPath, outputPdfPath);
    }


}

